package com.example.netty.linebase.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * <p></p>
 *
 * @author xin
 * @version 2023/11/2 16:39
 **/
public class LineBaseServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(LineBaseServerHandler.class);


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("收到客户端消息");
        try {
            String body = (String) msg;
            System.out.println("-----client start------| \n " + body + " \n| ------client end------");
            // 如果没有分割符 收不到消息；
            //客户端收到一条消息
            ctx.channel().writeAndFlush("我是服务端给客户端的消息;发送一次，收到一次\r\n");
        } catch (Exception e) {
            logger.error("接收数据异常", e);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    public static void main(String[] args) {
        System.out.println("我是服务端给客户端的消息;".getBytes(StandardCharsets.UTF_8).length);
    }
}
